<?php


namespace app\controller\admin;


use app\common\exception\ApiException;
use app\common\RedisKey;
use app\facade\RedisLocationFacade;
use app\model\config\RegionModel;
use app\model\partner\UserPartnerAreaModel;
use app\model\partner\UserPartnerModel;
use app\model\user\UserInvoiceModel;
use app\service\utils\GenerateUserNickService;
use app\service\utils\QqMapService;
use think\facade\Log;

class PartnerController extends BaseAdminController
{

    function setModel()
    {
        return new UserPartnerModel();
    }

    function setWithModel()
    {
        return ['region'];
    }

    function setSearch()
    {
        $where = [];
        $startTime = $this->request->param('start_time', '', 'trim');
        if ($startTime) {
            $where[] = ['create_time', '>=', strtotime($startTime)];
        }
        $endTime = $this->request->param('end_time', '', 'trim');
        if ($endTime) {
            $where[] = ['create_time', '<', strtotime($endTime) + 86400];
        }
        return [
            'like' => ['username', 'mobile', 'user_type', 'city'],
            '=' => ['type'],
            'custom' => $where
        ];
    }

    function setSort()
    {
        return ['id' => 'desc'];
    }

    public function save()
    {
        try {
            $data = $this->request->except(['create_time']);
            $id = $data['id'] ?? 0;;
            if (!isset($data['mobile']) || !$data['mobile']) {
                throw new ApiException('手机号不能为空');
            }
            if (!isset($data['birthday']) || !$data['birthday']) {
                throw new ApiException('请重新选择教练生日');
            }
            if (!isset($data['drive_time']) || !$data['drive_time']) {
                throw new ApiException('驾龄不能为空');
            }
            if (!isset($data['city']) || !$data['city']) {
                throw new ApiException('请选择城市');
            }
            if (!isset($data['address']) || !$data['address']) {
                throw new ApiException('请输入详细地址');
            }
            $fullAddress = RegionModel::where('id', $data['city'])->value('name') . $data['address'];
            $qqMapService = new QqMapService();
            $res = $qqMapService->getCoordinate($fullAddress);
            $lng = $res['lng'];
            $lat = $res['lat'];
            if (!$id) {
                if ($this->getModel()->where('mobile', $data['mobile'])->find()) {
                    throw new \Exception('账号已存在');
                }
                $data['password'] = 88888888;
                $data['birthday'] = strtotime($data['birthday']);
                $data['drive_time'] = strtotime($data['drive_time']);
                $data['username'] = $data['username'] ?: GenerateUserNickService::generateUserNick();
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $model = $this->setModel();
                $model->save($data);
                $id = $model->id;
            } else {
                $model = $this->setModel()->find($id);
                $data['birthday'] = strtotime($data['birthday']);
                $data['drive_time'] = strtotime($data['drive_time']);
                $data['lng'] = $lng;
                $data['lat'] = $lat;
                $model->save($data);
            }
            if ($lng && $lat) {
                RedisLocationFacade::setSchoolLocationToRedis(RedisKey::PARTNER_LOCATION_LIST, $id, $lng, $lat);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function status()
    {
        try {
            $id = $this->request->param('id', '', 'trim');
            $type = $this->request->param('type', '', 'trim');
            $model = $this->setModel()->find($id);
            $model->is_forbid = $type == 0 ? 1 : 0;
            $model->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function getArr()
    {
        $cityId = $this->request->param('city_id', 0);
        $type = $this->request->param('type', 0);
        $where = [];
        if ($cityId) {
            $where[] = ['city', '=', $cityId];
        }
        if ($type == 0) {
            $where[] = ['user_type', 'in', [0, 2]];
        } else {
            $where[] = ['user_type', 'in', [1, 2]];
        }
        $arr = $this->setModel()->where($where)->select()->toArray();
        return $this->success($arr);
    }

    /**
     * 获取区域列表
     * @return \think\response\Json
     */
    public function getAreaList()
    {
        try {
            $cityId = $this->request->param('city_id');
            $areaList = RegionModel::where('pid', $cityId)->select();
            return $this->success($areaList);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 添加教练服务区域
     * @return \think\response\Json
     */
    public function addArea()
    {
        try {
            $id = $this->request->param('partner_id');
            $city = $this->request->param('city');
            if (!$id) {
                throw new ApiException('请选择教练');
            }
            if (!is_array($city) || count($city) == 0) {
                throw new ApiException('请选择区域');
            }
            $userPartnerAreaModel = new UserPartnerAreaModel();
            $dataAll = [];
            foreach ($city as $k => $v) {
                $dataAll[$k] = [
                    'user_id' => $id,
                    'area_id' => $v,
                ];
            }
            $userPartnerAreaModel->saveAll($dataAll);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取用户区域
     * @return \think\response\Json
     */
    public function getUserArea()
    {
        try {
            $id = $this->request->param('partner_id');
            $userPartnerAreaModel = UserPartnerAreaModel::where('user_id', $id)->column('area_id');
            return $this->success($userPartnerAreaModel);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}